# -*- coding: UTF-8 -*-
from django_redis import get_redis_connection
from rest_framework import serializers
from .models import User, UserCart, UserCartDone, UserPinglun
import re
import logging
from rest_framework_jwt.settings import api_settings

log = logging.getLogger("django")


class UserModelSerializer(serializers.ModelSerializer):
    sms_code = serializers.CharField(write_only=True, max_length=6, min_length=6, label="手机短信", help_text="手机短信")
    token = serializers.CharField(read_only=True, label="jwt的token字符串")

    class Meta:
        model = User
        fields = ["mobile", "password", "sms_code", "token", "id", "username", "youMoney" ,"image"]
        extra_kwargs = {
            "id": {
                "read_only": True,
            },
            "username": {
                "read_only": True,
            },
            "password": {
                "write_only": True,
            },
            "mobile": {
                "write_only": True,
            }
        }

    # 验证手机号等
    def validate(self, data):
        # 接受数据
        mobile = data.get("mobile")
        sms_code = data.get("sms_code")
        password = data.get("password")

        # 验证手机格式
        if not re.match("^1[3|4|5|7|8][0-9]{9}$", mobile):
            raise serializers.ValidationError("手机格式不正确！")

        # 验证手机短信
        try:
            redis = get_redis_connection("sms_code")
        except:
            log.error("redis连接失败！")
            raise serializers.ValidationError("服务器出错，请再试一次！")
        # 验证短信是否正确
        try:
            real_sms_code = redis.get("sms_%s" % mobile).decode()
        except:
            raise serializers.ValidationError("手机短信不存在或已过期！")
        # 验证短信是否正确
        if sms_code != real_sms_code:
            raise serializers.ValidationError("手机短信错误！")
        else:
            redis.delete("sms_%s" % mobile)

        # 验证手机是否注册了
        try:
            User.objects.get(mobile=mobile)
            raise serializers.ValidationError("手机号码已经被注册！")
        except:
            pass

        # 验证密码长度
        if len(password) < 6 or len(password) > 20:
            raise serializers.ValidationError("密码必须保持在6-20位之间")

        # 必须返回数据
        return data

    # 创建账号
    def create(self, validated_data):
        mobile = validated_data.get("mobile")
        password = validated_data.get("password")
        try:
            user = User.objects.create_user(
                mobile=mobile,
                username=mobile,
                password=password
            )
            # 返回登入的jwt token值
        except:
            log.error("创建用户失败！mobile=%s" % mobile)
            raise serializers.ValidationError("注册用户失败！")

        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

        payload = jwt_payload_handler(user)
        user.token = jwt_encode_handler(payload)
        print(user)
        return user


class UserCartModelSerializer(serializers.ModelSerializer):
    # user_name = UserModelSerializer()

    class Meta:
        model = UserCart
        fields = [
            "id", "product_image", "product_name",
            "product_price", "introduce", "product_much",
            "user_name", "usercart_mobile","howManyToBuy"
        ]

    def create(self, validated_data):
        product_name = validated_data.get("product_name")
        product_price = validated_data.get("product_price")
        product_much = validated_data.get("product_much")
        introduce = validated_data.get("introduce")
        product_image = validated_data.get("product_image")
        user_name = validated_data.get("user_name")
        try:
            usercart = UserCart.objects.create(
                product_name=product_name,
                product_price=product_price,
                product_much=product_much,
                introduce=introduce,
                product_image=product_image,
                is_show=True,
                orders=True,
                user_name=user_name
            )
            # 返回登入的jwt token值
        except:
            log.error("添加商品失败！product_name=%s" % product_name)
            raise serializers.ValidationError("添加商品失败！")

        return usercart


class UserCartDoneModelSerializer(serializers.ModelSerializer):
    # user_name = UserModelSerializer()

    class Meta:
        model = UserCartDone
        fields = [
            "id", "product_image", "product_name",
            "product_price", "introduce", "product_much",
            "user_name", "usercart_mobile"
        ]

    def create(self, validated_data):
        product_name = validated_data.get("product_name")
        product_price = validated_data.get("product_price")
        product_much = validated_data.get("product_much")
        introduce = validated_data.get("introduce")
        product_image = validated_data.get("product_image")
        user_name = validated_data.get("user_name")
        try:
            usercartdone = UserCartDone.objects.create(
                product_name=product_name,
                product_price=product_price,
                product_much=product_much,
                introduce=introduce,
                product_image=product_image,
                is_show=True,
                orders=True,
                user_name=user_name
            )
            # 返回登入的jwt token值
        except:
            log.error("添加商品失败！product_name=%s" % product_name)
            raise serializers.ValidationError("添加商品失败！")

        return usercartdone


class UserPinglunModelSerializer(serializers.ModelSerializer):
    # user_name = UserModelSerializer()

    class Meta:
        model = UserPinglun
        fields = [
            "id", "content", "user_name", "product_name", "created_time", "usercart_mobile"
        ]

    def create(self, validated_data):
        content = validated_data.get("content")
        user_name = validated_data.get("user_name")
        product_name = validated_data.get("product_name")
        try:
            userpinglun = UserPinglun.objects.create(
                product_name=product_name,
                content=content,
                is_show=True,
                orders=True,
                user_name=user_name
            )
            # 返回登入的jwt token值
        except:
            log.error("添加评论成功！product_name=%s" % product_name)
            raise serializers.ValidationError("添加评论成功！")

        return userpinglun

